package com.mes.controller;

import com.yy.base.common.service.EntityService;
import com.yy.base.page.Message;
import com.yy.base.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/CPKRequestController")
public class CPKRequestController {
	private static int countSize = 0;
	private List updateIDS  = new ArrayList();
	@Autowired
	private EntityService service;

	/**
	 * 存储CPK
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/CPKReciver", method=RequestMethod.POST)
	public Message CPKReciver(HttpServletRequest request, HttpServletResponse response){
		Message msg = new Message();
		//"dat=" &dat 
		//&"&origin=" &origin &"&ban=" &ban &"&guanh=" &guanh &"&zhouh=" &zhouh &"&avrmh=" &avrmh &"&avrzsl=" &avrzsl &"&beizhu=" &beizhu &"&pos=" &pos &"&ret1=" &ret1 &"&ret2="  &ret2 
//		String dat = ;
//		String  = request.getParameter("origin"); //片源
//		String  = request.getParameter("ban");   //班组
//		String guanh = request.getParameter("guanh");  //管号
//		String zhouh = request.getParameter("zhouh");  //舟号
//		String avrmh = request.getParameter("avrmh"); //平均膜后
//		String avrzsl = request.getParameter("avrzsl"); //平均折射率
//		String beizhu = request.getParameter("beizhu"); //备注
//		String pos = request.getParameter("pos");    //位置
//		String ret1 = request.getParameter("ret1");   //膜后
//		String ret2 = request.getParameter("ret2");  //折射率
		
		Map params = new HashMap();
		String workshop = request.getParameter("chang");
		params.put("dat", request.getParameter("dat"));
		params.put("origin", request.getParameter("origin"));
		params.put("ban", request.getParameter("ban"));
		params.put("guanh", request.getParameter("guanh"));
		params.put("zhouh", request.getParameter("zhouh"));
		params.put("avrmh", request.getParameter("avrmh"));
		params.put("avrzsl", request.getParameter("avrzsl"));
		params.put("beizhu", request.getParameter("beizhu"));
		params.put("pos", request.getParameter("pos"));
		params.put("ret1", request.getParameter("ret1"));
		params.put("ret2", request.getParameter("ret2"));
		//表面镀膜(PECVD) 工序  DF20A3B7999F4144B7A92AB0A176F4EE 为五厂的工序ID
		params.put("processId","5".equals(workshop) ? "DF20A3B7999F4144B7A92AB0A176F4EE": "1D73723958214BBF8F897FFC378F8BE9");
		
		String curIpAddress = getIpAddr(request);
		String[] orgIds = {"4BAD2EB3B9B844FAABCDDD744E529F55","7B441EB01848477687A8ADE94F1F5F2A"};//四厂，五厂
		String curOrgId = orgIds[1];
		if(curIpAddress.contains("192.168.127")){//四厂
			curOrgId = orgIds[0];
		}else if(curIpAddress.contains("192.168.52")){
			curOrgId = orgIds[1];
		}
		curOrgId = "5".equals(workshop) ? orgIds[1] : orgIds[0];
		//检查
		boolean flag = getInfo( request.getParameter("guanh"),request.getParameter("zhouh"),request.getParameter("pos"));
		String pos = orgIds[1].equals(curOrgId) ? "7f" : "8f";
		int totalNum = orgIds[1].equals(curOrgId) ? 6 : 7;
		if("".equalsIgnoreCase(request.getParameter("ret1"))|| null == request.getParameter("ret1")){
			
		}else{
			if(!flag){
				if(!request.getParameter("pos").equalsIgnoreCase(pos)){ //如果更新的是前6f，则只更新值
					updateData(params,true);
				}else{ //否则更新平均值
					updateData(params,false);
				}
			}else{
				if(request.getParameter("pos").equalsIgnoreCase(pos)){//7号位置进行数据更新
					if(checkCount(request.getParameter("guanh"),request.getParameter("zhouh"))==totalNum){//检查前面是否已检查6个数据
						insertData(params,curOrgId);
						updateData(params,false);
					}
				}else{
					insertData(params,curOrgId);
				}
			}
			 
		}
		
		
		return msg;
	}
	
	/**
	 * 存储CPK
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/MHZSLReciver", method=RequestMethod.POST)
	public Message MHZSLReciver(HttpServletRequest request, HttpServletResponse response){
		Message msg = new Message();
		System.out.println("!!!!!!!!!!!!!!!");
		return msg;
	}
	
	
	
	
	public Message insertData(Map map,String orgId){
		Message msg = new Message();
		
		String uuid = StringUtil.getUUID();
		
		String sql = " insert into Emeso_QUALITY_MH " +
				 "(  "+
				 "	  emeso_quality_mh_id, "+
				 "	  test_date, "+
				 "	  guanno, "+
				 "	  zhouno, "+
				 "	  position, "+
				 "	  thicknesst, "+
				 "	  refractive_index, "+
				 "	  avg_thick, "+
				 "	  avg_index, "+
				 "	  description, "+
				 "	  ad_org_id, "+
				 " 	  ad_client_id, "+
				 "	  isactive, "+
				 "	  created, "+
			 	 "	  createdby, "+
				 "	  updated, "+
				 "	  updatedby, "+
				 "	  Eam_Facilities_id, "+
				 "	  emes_process_id "+
				 ") select '"+uuid +"',"
			+ "now(),'"
			+ map.get("guanh") + "','" 
			+ map.get("zhouh") + "','"
			+ map.get("pos") + "','" 
			+ map.get("ret1") + "','" 
			+ map.get("ret2")  
			+ "','AVRAGEMH','AVRAGEZSL','" 
			+ map.get("beizhu") +"'," +
			"'"+orgId+"','109695EA6D204270953EBF6EC5731DBD'," + 
			"'Y',now()," +
			"'FB5A99A980344F51998CA18E846FF455',now()," +
			"'FB5A99A980344F51998CA18E846FF455','','"+map.get("processId")+"' from dual";
			
			System.out.println(sql);
			
			try {
				service.executeSql(sql);
			} catch (Exception e) {
				// TODO: handle exception
			}
		
		return null;
	}
	
	/**
	 * 更新平均膜后折射率
	 * @param zhouh
	 * @param guanh
	 * @param avgmh
	 * @param avgzsl
	 * @return
	 */
	public Message updateAVGInfo(String zhouh,String guanh,String avgmh,String avgzsl){
		
		Message msg = new Message();
		
		String updateSql = " update Emeso_QUALITY_MH mh set mh.avg_thick = ? , mh.avg_index = ? ,mh.finish = 'Y' where mh.finish = 'N' and mh.guanno = ? and mh.zhouno = ?  ";
		
		try {
			service.executeSql(updateSql, avgmh,avgzsl,guanh,zhouh);
			msg.setOkMessage("存储成功。");
		} catch (Exception e) {
			// TODO: handle exception
			msg.setErrorMessage("存储失败："+e.getStackTrace());
		}
		
		return msg;
	}
	
	/**
	 * 检查是否重复插入
	 * @param guanh
	 * @param zhouh
	 * @param pos
	 * @return
	 */
	public boolean getInfo(String guanh,String zhouh,String pos){
		String checkSql = " select count(*) from Emeso_QUALITY_MH mh where mh.finish = 'N' and mh.guanno = ? and mh.zhouno = ? and mh.POSITION = ? and mh.TEST_DATE>=(sysdate-1/12) ";
		Long count = service.getSqlCount(checkSql, guanh,zhouh,pos);
		if(count == 0 || count == null){
			return true;
		}else{
			return false;
		}
		
	}
	
	/**
	 * 
	 * @param params
	 * @return
	 */
	public int updateData(Map params,boolean flag){
		
		if(flag){
			String checkSql = " update Emeso_QUALITY_MH mh set  "
					+ "  mh.thicknesst = ? "
					+ ", mh.refractive_index = ? "
					+ "where mh.finish = 'N' and mh.guanno = ? and mh.zhouno = ? and mh.POSITION = ?";
			service.executeSql(checkSql, params.get("ret1"),params.get("ret2"),params.get("guanh"),params.get("zhouh"),params.get("pos"));
			
		}else{
			String groupId = StringUtil.getUUID();
			String checkSql = " update Emeso_QUALITY_MH mh set mh.avg_thick = ? "
					+ ", mh.avg_index = ? "
					+ ",mh.finish = 'Y' "
					+ ",GROUP_ID = ? "
					+ "where mh.finish = 'N' and mh.guanno = ? and mh.zhouno = ? ";
			service.executeSql(checkSql, params.get("avrmh"),params.get("avrzsl"),groupId,params.get("guanh"),params.get("zhouh"));
		}
		
		return 1;
	}
	
	private long checkCount(String guanh,String zhouh){
		String checkSql = " select count(*) from Emeso_QUALITY_MH mh where mh.finish = 'N' and mh.guanno = ? and mh.zhouno = ? and mh.TEST_DATE>=(sysdate-1/12) ";
		Long count = service.getSqlCount(checkSql, guanh,zhouh);
		return count;
	}
	
	//获取ip
	private String getIpAddr(HttpServletRequest request) { 
	    String ip = request.getHeader("x-forwarded-for"); 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getRemoteAddr(); 
	    } 
	    return ip; 
	}
}
